package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.*;
import com.gqj.meter.mapper.MdConcentratorMapper;
import com.gqj.meter.mapper.MdInTaskDetailsMapper;
import com.gqj.meter.mapper.MdItMapper;
import com.gqj.meter.mapper.MdMeterMapper;
import com.gqj.meter.service.IMdInTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 出入库任务Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdInTask", description = "入库任务")
@RestController
@RequestMapping("/meter/mdInTask")
public class MdInTaskController extends BaseController {
    @Autowired
    private IMdInTaskService mdInTaskService;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdMeterMapper mdMeterMapper;
    @Autowired
    private MdItMapper mdItMapper;
    @Autowired
    private MdConcentratorMapper mdConcentratorMapper;

    /**
     * 查询出入库任务列表
     */
    @ApiOperation("查询入库任务列表")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdInTask mdInTask) {
        startPage();
        List<MdInTask> list = mdInTaskService.selectMdInTaskList(mdInTask);

        return getDataTable(list);
    }

    /**
     * 导出出入库任务列表
     */
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:export')")
    @Log(title = "入库任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdInTask mdInTask) {
        List<MdInTask> list = mdInTaskService.selectMdInTaskList(mdInTask);
        ExcelUtil<MdInTask> util = new ExcelUtil<MdInTask>(MdInTask.class);
        util.exportExcel(response, list, "出入库任务数据");
    }

    /**
     * 获取出入库任务详细信息
     */
    @ApiOperation("获取入库任务详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:query')")
    @GetMapping(value = "/{inTaskId}")
    public AjaxResult getInfo(@PathVariable("inTaskId") Long inTaskId) {
        return success(mdInTaskService.selectMdInTaskByInTaskId(inTaskId));
    }

    /**
     * 新增出入库任务
     */
    @ApiOperation("新增入库任务")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:add')")
    @Log(title = "入库任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdInTask mdInTask) {
        mdInTask.setOperationUserId(getUserId());
        mdInTask.setInTaskNo("RK-" + StorageUtil.getOrderNoTo12());
        return toAjax(mdInTaskService.insertMdInTask(mdInTask));
    }

    /**
     * 修改出入库任务
     */
    @ApiOperation("修改入库任务")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:edit')")
    @Log(title = "入库任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdInTask mdInTask) {
        if (UserConstants.NOT_UNIQUE.equals(mdInTaskService.checkInTaskNoUnique(mdInTask))) {
            return AjaxResult.error("修改'" + mdInTask.getInTaskNo() + "'任务失败，任务编号已存在");
        }
        MdInTask mdInTaskTemp = mdInTaskService.selectMdInTaskByInTaskId(mdInTask.getInTaskId());
        if (!"0".equals(mdInTaskTemp.getStatusCode())) {
            return AjaxResult.error("修改'" + mdInTask.getInTaskNo() + "'任务失败，任务已执行不允许修改");
        }
        return toAjax(mdInTaskService.updateMdInTask(mdInTask));
    }

    /**
     * 删除出入库任务
     */
    @ApiOperation("删除入库任务")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:remove')")
    @Log(title = "入库任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{inTaskIds}")
    public AjaxResult remove(@PathVariable Long[] inTaskIds) {
        for (Long inTaskId : inTaskIds) {
            MdInTask mdInTask = mdInTaskService.selectMdInTaskByInTaskId(inTaskId);
            if ("1".equals(mdInTask.getStatusCode())) {
                return AjaxResult.error("删除'" + mdInTask.getInTaskNo() + "'任务失败，任务已执行不允许删除");
            }
        }
        return toAjax(mdInTaskService.deleteMdInTaskByInTaskIds(inTaskIds));
    }

    /**
     * 修改出入库任务状态
     */
    @ApiOperation("修改入库任务状态")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:editStatus')")
    @Log(title = "入库任务", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus")
    public AjaxResult editStatus(@RequestBody MdInTask mdInTask) {
        return toAjax(mdInTaskService.updateMdInTask(mdInTask));
    }

    /**
     * 查询出入库统计信息
     */
    @ApiOperation("查询出入库统计信息")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:mdIoStatistics')")
    @GetMapping("/getIoStatisticsInfo")
    public AjaxResult getIoStatisticsInfo() {
        Map<String, Object> map = mdInTaskService.getIoStatisticsInfo();
        return success(map);
    }

    /**
     * 下载入库单json文件
     */
    @ApiOperation("下载入库json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdInTask:downloadJsonMdInTask')")
    @GetMapping("/downloadJsonMdInTask")
    public AjaxResult downloadJsonMdInTask(MdInTask mdInTask) {
        //只下载任务开始的单据
        mdInTask.setStatusCode("1");
        Long[] inTaskIds = mdInTask.getInTaskIds();
        for (int i = 0; i < inTaskIds.length; i++) {
            MdInTask inTask = mdInTaskService.selectMdInTaskByInTaskId(inTaskIds[i]);
            if (!"1".equals(inTask.getStatusCode())) {
                return AjaxResult.error("单据" + inTask.getInTaskNo() + "不是开始开始执行状态，请重新选择!");
            }
        }
        List<MdInTask> pos = mdInTaskService.selectMdInTaskList(mdInTask);

        for (MdInTask p : pos) {
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(new MdInTaskDetails() {{
                setInTaskNo(p.getInTaskNo());
            }});
            p.setMdInTaskDetailsList(mdInTaskDetailsList);
        }
        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(pos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "入库单数据" + orderNo);
        return AjaxResult.success(fileName + "入库单数据" + orderNo);
    }
}
